package com.ydsungan.controller;


import com.ydsungan.pojo.*;
import com.ydsungan.service.BookService;
import com.ydsungan.service.HomeService;
import com.ydsungan.common.JSONResult;



import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

@RestController
@RequestMapping(path = "/home")
@Api(value = "首页相关",tags = {"与首页相关的接口"})
@Slf4j
public class HomeController extends BasicController{

    @Autowired
    private HomeService homeService;

    @Autowired
    private BookService bookService;



    @ApiOperation(value="首页滚动通知栏",notes = "动态显示首页的通知")
    @RequestMapping(value = "/inform", method = RequestMethod.GET)
    public JSONResult saveDate() throws Exception{
        InformExample informExample = new InformExample();
        InformExample.Criteria  criteria = informExample.createCriteria();
        criteria.andOnShowEqualTo(1);
        List<Inform> informList = homeService.listInform(informExample);
        return JSONResult.ok(informList);
    }

    @ApiOperation(value="对每日一问点赞",notes = "点赞写入数据库")
    @RequestMapping(value = "/like", method = RequestMethod.GET)
    public JSONResult addDailyLike(String openId, String dailyId) throws Exception{
        homeService.addDailyLike(openId, Integer.parseInt(dailyId));
        return JSONResult.ok();
    }

    @ApiOperation(value="获取版本更新历史记录",notes = "获取版本更新历史记录")
    @RequestMapping(value = "/version", method = RequestMethod.GET)
    public JSONResult getVersionRecords() throws Exception{

        return JSONResult.ok(homeService.listVersionRecords());
    }


    @ApiOperation(value="对每日一问收藏",notes = "收藏写入数据库")
    @RequestMapping(value = "/collect", method = RequestMethod.GET)
    public JSONResult addDailyCollect(String openId, String dailyId, String type) throws Exception{
        homeService.addDailyCollect(openId, Integer.parseInt(dailyId), type);
        return JSONResult.ok();
    }

    @ApiOperation(value="首页每日一问",notes = "首页问题")
    @RequestMapping(value = "/daily", method = RequestMethod.GET)
    public JSONResult getDailyQuestion(String openId) throws Exception{


        //如果今天的daily已经生成了，就直接获取，如果没有则随机选择一个问题再生成
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String today = df.format(new Date());
        String todayStart = today + " 00:00:00";
        SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date dateTime = null;
        try {
            dateTime = df2.parse(todayStart);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        DailyExample dailyExample = new DailyExample();
        DailyExample.Criteria criteria = dailyExample.createCriteria();
        criteria.andCreateTimeBetween(dateTime, new Date());
        List<Daily> dailyList = homeService.selectDailyByExample(dailyExample);

        DailyVO dailyVO = new DailyVO();
        if(dailyList.size() == 0){
            DailyQuestionExample dailyQuestionExample = new DailyQuestionExample();
            int counts = (int)homeService.countByExample(dailyQuestionExample);
            //产生一个1 - counts之间的随机数
            Random random = new Random();
            int randomId =  random.nextInt(counts) + 1;
            DailyQuestion dailyQuestion = homeService.selectById(randomId);

            Daily daily = new Daily();
            daily.setQuestionId(randomId);
            daily.setCreateTime(new Date());
            homeService.insertDaily(daily);
            BeanUtils.copyProperties(daily, dailyVO);
            dailyVO.setQuestion(dailyQuestion.getQuestion());
            dailyVO.setAnswer(dailyQuestion.getAnswer());
            dailyVO.setLikeNum(0);
            dailyVO.setCollectionNum(0);
            dailyVO.setHasLiked(0);
            dailyVO.setHasCollected(0);

        }else{
            BeanUtils.copyProperties(dailyList.get(0), dailyVO);
            DailyQuestion dailyQuestion = homeService.selectById(dailyList.get(0).getQuestionId());
            dailyVO.setQuestion(dailyQuestion.getQuestion());
            dailyVO.setAnswer(dailyQuestion.getAnswer());
            dailyVO.setHasLiked(homeService.hasLikedDaily(openId, dailyList.get(0).getId()));
            dailyVO.setHasCollected(homeService.hasCollectedDaily(openId, dailyList.get(0).getId()));
            dailyVO.setCollectionNum(homeService.countDailyCollectNum(dailyList.get(0).getId()));
            dailyVO.setLikeNum(homeService.countDailyLikeNum(dailyList.get(0).getId()));
        }

        return JSONResult.ok(dailyVO);
    }

    @ApiOperation(value="获取每天需要复习的题目数量",notes = "首页复习")
    @RequestMapping(value = "/review", method = RequestMethod.GET)
    public JSONResult review(String openId) throws Exception{

        //这个用户使用了几本书？每本书有多少题？
        List<Book> bookList = bookService.selectUsingBook(openId);


        //怎么计算复习量？只复习错题
        //艾宾浩斯遗忘曲线：1天后，2天后，6天后，30天后
        //获取该用户错题，1天前的、2天前的，6天前的，30天前的，
        //比如6天前的错题应该在今天复习，但是今天没有复习，应该累计到明天复习
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date day = new Date();
        String dayString = df.format(day);

        List<ReviewVO> reviewVOList = new ArrayList<>();
        for(int  i = 0; i < bookList.size(); ++i){
            ReviewVO reviewVO = new ReviewVO();
            reviewVO.setAuthor(bookList.get(i).getAuthor());
            reviewVO.setBookId(bookList.get(i).getId());
            reviewVO.setBookName(bookList.get(i).getBookName());
            reviewVO.setCoverImg(bookList.get(i).getCoverImg());
            reviewVO.setAbbr(bookList.get(i).getAbbr());
            reviewVO.setPress(bookList.get(i).getPress());

            String key = "review:" + openId + ":" + dayString + ":" + bookList.get(i).getId();
            if(redis.get(key) == null){
                reviewVO.setReviewNum(homeService.countErrorQuestionNum(openId, bookList.get(i).getId()));
            }else{
                String redisValue = redis.get(key);
                reviewVO.setReviewNum(redisValue.split(",").length);
            }

            reviewVOList.add(reviewVO);
        }

        return JSONResult.ok(reviewVOList);
    }

    @ApiOperation(value="反馈",notes = "反馈信息提交")
    @RequestMapping(value = "/feedback", method = RequestMethod.GET)
    public JSONResult feedback(String openId, String content) throws Exception{
        log.info("feedback: openId = {}; content = {}", openId, content);
        Feedback feedback = new Feedback();
        feedback.setCreateTime(new Date());
        feedback.setFeedbackText(content);
        feedback.setUserId(openId);
        homeService.feedBack(feedback);
        return JSONResult.ok();
    }

    @ApiOperation(value="收藏",notes = "获取收藏列表")
    @RequestMapping(value = "/listcollect", method = RequestMethod.GET)
    public JSONResult listCollection(String openId) throws Exception{

        return JSONResult.ok(homeService.listCollect(openId));
    }

    @ApiOperation(value="分享",notes = "保存用户分享的内容")
    @RequestMapping(value = "/share", method = RequestMethod.GET)
    public JSONResult addShare(String openId, String fileName, String description, String link) throws Exception{

        Share share = new Share();
        share.setCreateTime(new Date());
        share.setFileName(fileName);
        share.setUserId(openId);
        share.setStatus(-1);
        share.setDescription(description);
        share.setLink(link);
        homeService.insertShareRecord(share);
        return JSONResult.ok();
    }

    @ApiOperation(value="获取分享列表",notes = "获取展示用户分享的内容")
    @RequestMapping(value = "/listshare", method = RequestMethod.GET)
    public JSONResult listShare(String openId) throws Exception{
        return JSONResult.ok(homeService.listShare(openId));
    }


    @ApiOperation(value="获取设置",notes = "获取一些设置数据")
    @RequestMapping(value = "/setting", method = RequestMethod.GET)
    public JSONResult listSettings() throws Exception{
        String showUpload = redis.get("showUpload");
        JSONObject object = new JSONObject();
        object.put("showUpload", showUpload == null ? "0" : showUpload);
        return JSONResult.ok(object.toString());
    }




}
